﻿

using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gift.Utile;
using Gift.Model;
using Gift.DAL;
using System.Web.Security;
using System.Data;


    public partial class admin_company_CompanyManager : BaseAdmin
    {
        readonly dalCompany theCompany = new dalCompany();
        readonly DALAdminLogin theAdminLogin = new DALAdminLogin();
        readonly DALRoleRuleRef theUserRuleRef = new DALRoleRuleRef();
        readonly DALRule theRule = new DALRule();
        public int ParaCompanyId
        {
            get {
                if (string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    return -1;
                }
                else
                {
                    return int.Parse(Request.QueryString["id"]);
                }
            }
        }
        public string Action
        {
            get
            {
                return Request.QueryString["action"];
               
            }
        }

        string ParamentType
        {
            get
            {
                if(string.IsNullOrEmpty( Request.QueryString["type"]))
                {
                    return string.Empty;
                }else
                {
                    return Request.QueryString["type"];
                }
            }
        }


        public void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (ParamentType == "publish")
                {
                    trUpCompany.Visible = false;
                    this.ddlCompanyLevel.Enabled = false;
                    base.ValidateLoginRule(Gift.Model.ENUM.ERule.AddPublishCompany);
                }
                else if (base.CompanyId == null )
                {
                    base.ValidateLoginRule(Gift.Model.ENUM.ERule.AddCompany);
                }

                if (ParaCompanyId > -1 && base.CompanyId != null)
                {
                    this.txtName.Enabled = false;
                    this.txtShortName.Enabled = false;
                    this.txtCompanyCode.Enabled = false;
                    this.txtManager.Enabled = false;
                    this.txtManagerMobile.Enabled = false;
                    this.AddressArea1.Visible = false;
                    this.txtAddress.Enabled = false;
                    this.ddlUpCompany.Enabled = false;
                    this.ddlCompanyLevel.Enabled = false;
                    if (ParaCompanyId.ToString() == base.CompanyId)
                    {
                        this.txtOnSale.Enabled = false;
                    }
                }

                this.BindCompanyList();
                this.BindCompanyLevel();
                this.BuildForm();
            }
        }

        void BuildForm()
        {
            if (Action == "del")
            {
                if (base.CompanyId != null && base.CompanyId == ParaCompanyId.ToString())
                {
                    base.Response.Write("<script language='javascript'>alert('不能删除自己！');window.location.href='companyList.aspx?type=" + ParamentType + "';</script>");
                    base.Response.End();
                }
                else
                {
                    if (theCompany.ExistsDownCompany(ParaCompanyId))
                    {
                        base.Response.Write("<script language='javascript'>alert('您有下级商家，如要删除，请先删除下级商家！');window.location.href='companyList.aspx?type=" + ParamentType + "';</script>");
                        base.Response.End();
                    }
                    else
                    {
                        theCompany.Delete(ParaCompanyId);
                        base.Response.Write("<script language='javascript'>alert('删除成功！');window.location.href='companyList.aspx?type=" + ParamentType + "';</script>");
                        base.Response.End();
                    }
                }
            }

            else if (ParaCompanyId >= 0)
            {
                tbCompany oCompany;
                oCompany = theCompany.GetModel(ParaCompanyId);
                if (theCompany != null)
                {
                    if (base.CompanyId != null)
                    {
                        this.txtAddress.Text = oCompany.Provence + "," + oCompany.Area + "," + oCompany.Address;
                    }
                    else
                    {
                        this.txtAddress.Text = oCompany.Address;
                    }
                    this.txtEmail.Text = oCompany.Email;
                    this.txtFax.Text = oCompany.Fax;
                    this.txtLinker.Text = oCompany.Linker;
                    this.txtName.Text = oCompany.Name;
                    this.hdCompany.Value = oCompany.Name;
                    this.txtPostcode.Text = oCompany.Postcode;
                    this.txtQQ.Text = oCompany.QQ;
                    this.txtTel.Text = oCompany.Telephone;
                    this.ddlCompanyType.Items.FindByValue(oCompany.CompanyTypeId.ToString()).Selected = true;
                    if (oCompany.LevelId == 0)
                    {
                        this.ddlCompanyLevel.Items.Insert(0, new ListItem("顶级", "0"));
                    }
                        this.ddlCompanyLevel.Items.FindByValue(oCompany.LevelId.ToString()).Selected = true;

                    this.txtOnSale.Text = theCompany.GetCompanyOnSale(oCompany.Id.ToString()).ToString();
                    this.txtMobile.Text = oCompany.Mobile;
                    this.txtCompanyCode.Text = oCompany.CompanyCode;
                    this.txtShortName.Text = oCompany.CompanyShortName;
                    this.txtManager.Text = oCompany.CompanyManager;
                    this.txtManagerMobile.Text = oCompany.CompanyManagerMobile;
                    if (this.ddlUpCompany.Items.FindByValue(oCompany.ParentId.ToString()) != null)
                    {
                        this.ddlUpCompany.Items.FindByValue(oCompany.ParentId.ToString()).Selected = true;
                    }

                    if (base.CompanyId == ParaCompanyId.ToString())
                    {
                        this.ddlCompanyLevel.Enabled = false;
                        this.txtOnSale.Enabled = false;
                        this.txtUserName.Text = base.AdminUser;
                    }
                    else
                    {
                        this.trLoginPwd.Visible = false;
                        this.trLoginUser.Visible = false;
                    }
                    if (oCompany.LevelId == 1)
                    {
                        this.ddlCompanyLevel.Enabled = false;
                        this.trUpCompany.Visible = false;
                    }
                    this.AddressArea1 .SetProvence(oCompany.Provence);
                    this.AddressArea1.SetArea(oCompany.Area);
                
                    //this.trLoginPwd.Visible = false;
                    //DB_adminlogin oAdminLogin;
                    //oAdminLogin = theAdminLogin.GetModel(int.Parse(base.AdminUserId));
                    //if (oAdminLogin != null)
                    //{
                    //    this.txtUserName.Text = oAdminLogin.AdminUser;
                    //    this.hdLoginUser.Value = this.txtUserName.Text.Trim();
                    //}
                    this.txtUserName.Enabled = false;
                }
            }
            else
            {
                this.txtCompanyCode.Text = theCompany.GetGenerateCompanyCode(ParamentType == "publish").ToString();      
            }
        }

        public void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            tbCompany oCompany;
            DB_AdminLogin oAdminLogin;
            oCompany = null;
            if (ParaCompanyId > -1)
            {
                oCompany = theCompany.GetModel(ParaCompanyId);
            }

            if (oCompany == null) oCompany = new tbCompany();
            tbCompany oUpCompany = theCompany.GetModel(int.Parse(this.ddlUpCompany.SelectedItem.Value));
      
            try
            {
               double dSale =  double.Parse(this.txtOnSale.Text.Trim());
               if ((dSale < 0.5 || dSale > 1.0) && base.LevelId != "0" && base.LevelId != "1")
               {
                   base.Response.Write("<script language='javascript'>alert('折扣只能为0.50-1.00的数字！');</script>");
                   return;
               }
            }
            catch
            {
                base.Response.Write("<script language='javascript'>alert('折扣只能为0.50-1.00的数字！');</script>");
                return;
            }


            oCompany.Id = ParaCompanyId;

            oCompany.Email = this.txtEmail.Text.Trim();
            oCompany.Linker = this.txtLinker.Text.Trim();
            oCompany.Fax = this.txtFax.Text.Trim();
            oCompany.Name = this.txtName.Text.Trim();
            oCompany.Postcode = this.txtPostcode.Text.Trim();
            oCompany.QQ = this.txtQQ.Text.Trim();
            oCompany.Telephone = this.txtTel.Text.Trim();
            if (ParamentType == "publish")
            {
                oCompany.ParentId = 0;
            }
            else
            {
                if ((oCompany.ParentId != 0 || ParaCompanyId == -1) && oCompany.ParentId != -1)
                {
                    oCompany.ParentId = this.ddlUpCompany.SelectedItem.Value == "" ? 0 : int.Parse(this.ddlUpCompany.SelectedItem.Value);
                }
            
            }
            oCompany.LevelId = int.Parse(this.ddlCompanyLevel.SelectedItem.Value);
            oCompany.Mobile = this.txtMobile.Text.Trim();
            oCompany.CompanyTypeId = int.Parse(this.ddlCompanyType.SelectedItem.Value);
            oCompany.CompanyCode = this.txtCompanyCode.Text.Trim();
            oCompany.CompanyShortName = this.txtShortName.Text.Trim();
            oCompany.CompanyManager = this.txtManager.Text.Trim();
            oCompany.CompanyManagerMobile = this.txtManagerMobile.Text.Trim();

            try
            {
                if (ParaCompanyId >= 0)
                {
                    if (base.CompanyId == null)
                    {
                        oCompany.Provence = this.AddressArea1.GetProvence();
                        oCompany.Area = this.AddressArea1.GetArea();
                        oCompany.Address = this.txtAddress.Text.Trim();
                    }

                    if (theCompany.ExistsByCode(this.txtCompanyCode.Text.Trim()) && oCompany.CompanyCode != this.txtCompanyCode.Text.Trim())
                    {
                        base.Response.Write("<script language='javascript'>alert('系统中已有此公司编码，请重新设置编码！');</script>");
                        this.txtCompanyCode.Text = theCompany.GetGenerateCompanyCode(ParamentType == "publish").ToString();      
                        return;
                    }

                    if (this.hdCompany.Value != oCompany.Name)
                    {
                        tbCompany tempCompany = theCompany.GetModelByName(oCompany.Name);
                        if (tempCompany != null)
                        {
                            base.Response.Write("<script language='javascript'>alert('该公司名已存在,请重新输入公司名!');</script>");
                            return;
                        }
                    }
                    if (oCompany.CompanyShortName != this.txtShortName.Text.Trim()
                         && theCompany.ExistsByShortName(this.txtShortName.Text.Trim()))
                    {
                        base.Response.Write("<script language='javascript'>alert('该公司简称已存在,请重新输入公司简称!');</script>");
                        return;
                    }

                    if (oUpCompany.LevelId >= int.Parse(this.ddlCompanyLevel.SelectedItem.Value) && oCompany.LevelId != 1 && oCompany.LevelId != 0)
                    {
                        base.Response.Write("<script language='javascript'>alert('上级公司级别不能小于添加的公司级别！');</script>");
                        return;
                    }

                    oAdminLogin =  new DB_AdminLogin();

                    //if (this.hdLoginUser.Value != this.txtUserName.Text.Trim())
                    //{
                    //    int iAdminId = theAdminLogin.GetIdByName(this.txtUserName.Text.Trim());
                    //    if (iAdminId > 0)
                    //    {
                    //        base.Response.Write("<script language='javascript'>alert('该用户名已存在,请重新输入用户名!');</script>");
                    //        return;
                    //    }
                    //    oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                    //    oAdminLogin.AdminPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                    //    iAdminId = theAdminLogin.Add(oAdminLogin);
                    //    oAdminLogin.AdminId = iAdminId;
                    //}
                    if(base.CompanyId == ParaCompanyId.ToString())
                    {
                        int iAdminId = theAdminLogin.GetIdByName(this.txtUserName.Text.Trim());

                        if (iAdminId <= 0)
                        {
                            oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                            oAdminLogin.AdminPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                            iAdminId = theAdminLogin.Add(oAdminLogin);
                            oAdminLogin.AdminId = iAdminId;
                        }
                        else
                        {
                            oAdminLogin.AdminId = iAdminId;
                            oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                            if (!string.IsNullOrEmpty(this.txtPassword.Text.Trim()))
                            {
                                oAdminLogin.AdminPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                                theAdminLogin.Update(oAdminLogin);
                            }

                        }
                    }


                    theCompany.Update(oCompany);

                    theCompany.IsExistsOnSale(oCompany.Id.ToString(), float.Parse(this.txtOnSale.Text.Trim()));
            
                }
                else
                {
                    oCompany.Provence = this.AddressArea1.GetProvence();
                    oCompany.Area = this.AddressArea1.GetArea();
                    oCompany.Address = this.txtAddress.Text.Trim();

                    tbCompany tempCompany = theCompany.GetModelByName(oCompany.Name);
                    if (tempCompany != null)
                    {
                        base.Response.Write("<script language='javascript'>alert('该公司名已存在,请重新输入公司名!');</script>");
                        return;
                    }

                    if (theCompany.ExistsByShortName(this.txtShortName.Text.Trim()))
                    {
                        base.Response.Write("<script language='javascript'>alert('该公司简称已存在,请重新输入公司简称!');</script>");
                        return;
                    }

                    if (theCompany.ExistsByCode(this.txtCompanyCode.Text.Trim()))
                    {
                        base.Response.Write("<script language='javascript'>alert('系统中已有此公司编码，请重新设置编码！');</script>");
                        this.txtCompanyCode.Text = theCompany.GetGenerateCompanyCode(ParamentType == "publish").ToString();      
                        return;
                    }
                    oAdminLogin = new DB_AdminLogin();
                  
                    int iAdminId = theAdminLogin.GetIdByName(this.txtUserName.Text.Trim());
                    if (iAdminId > 0)
                    {
                        base.Response.Write("<script language='javascript'>alert('该用户名已存在,请重新输入用户名!');</script>");
                        return;
                    }

                    if (oUpCompany.LevelId >= int.Parse(this.ddlCompanyLevel.SelectedItem.Value) && oCompany.LevelId != 1)
                    {
                        base.Response.Write("<script language='javascript'>alert('上级公司级别不能小于添加的公司级别！');</script>");
                        return;
                    }

                    if (this.txtPassword.Text.Trim() == "" || this.txtConfirmPass.Text.Trim() == "")
                    {
                        base.Response.Write("<script language='javascript'>alert('密码不能为空！');</script>");
                        return;
                    }
                    oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                    oAdminLogin.AdminPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                    iAdminId = theAdminLogin.Add(oAdminLogin);


                    theCompany.Add(oCompany);

                    DataSet ds = theRule.GetCompanyRuleList();
                    StringBuilder sbIds = new StringBuilder();
                    foreach(DataRow dr in ds.Tables[0].Rows)
                    {
                        sbIds.Append(","+dr["id"].ToString());
                    }

                    theUserRuleRef.SaveCompanyRule(iAdminId, sbIds.ToString().Substring(1, sbIds.Length - 1));
                    oCompany = theCompany.GetModelByName(oCompany.Name);
                    SQLAccess.DoSql(string.Format("insert into tbCompanyAdmin(CompanyId,AdminId) values({0},{1});"
                                    ,oCompany.Id,iAdminId.ToString()));
                    
                    theCompany.IsExistsOnSale(oCompany.Id.ToString(), float.Parse(this.txtOnSale.Text.Trim()));
                  
                }
                base.Response.Write("<script language='javascript'>alert('保存成功');window.location.href='companyList.aspx?type=" + ParamentType+"';</script>");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }

        }

        void BindCompanyLevel()
        {
            DataSet ds = theCompany.GetListForCompanyLevel();
            this.ddlCompanyLevel.DataTextField = "LevelName";
            this.ddlCompanyLevel.DataValueField = "Id";
            if (ds != null && ds.Tables.Count > 0)
            {
                if (ParamentType == "publish")
                {
                    ds.Tables[0].DefaultView.RowFilter = "Id =1";
                }
                else
                {
                    if (base.CompanyId == ParaCompanyId.ToString())
                    {
                        ds.Tables[0].DefaultView.RowFilter = "Id >=" + base.LevelId;
                    }
                    else
                    {
                        ds.Tables[0].DefaultView.RowFilter = "Id >" + base.LevelId;
                    }
                    if (ParaCompanyId >= 0)
                    {
                        tbCompany oCompany = theCompany.GetModel(ParaCompanyId);
                        if (oCompany.LevelId != 1)
                        {
                            ds.Tables[0].DefaultView.RowFilter = "Id >1";
                        }
                    }
                    else
                    {
                        ds.Tables[0].DefaultView.RowFilter = "Id >1";
                    }
                }

                this.ddlCompanyLevel.DataSource = ds.Tables[0].DefaultView;
                this.ddlCompanyLevel.DataBind();
            }
        }

        void BindCompanyList()
        {
            DataTable dt;
            string sWhere = " 1=1 ";
            dt = theCompany.GetList(sWhere).Tables[0];
            if (base.CompanyId != null)
            {
                if (ParaCompanyId >= 0)
                {
                    dt = GetAllCompany(dt, null, 0, true);
                }
                else
                {
                    dt = GetAllCompany(dt, null, int.Parse(base.CompanyId), false);
                }
            }
            else
            {
              
                dt = GetAllCompany(dt, null, 0, true);
            }
            this.ddlUpCompany.DataTextField = "Name";
            this.ddlUpCompany.DataValueField = "Id";
            this.ddlUpCompany.DataSource = dt;
            this.ddlUpCompany.DataBind();

            if (ParaCompanyId < 0 && base.CompanyId != null)
            {
                this.ddlUpCompany.Items.FindByValue(base.CompanyId).Selected = true;
            }
        }
    }
